<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Api\Repositories\WxContRepositories;

use App\Models\Pets\WxPetsAdoption;
use App\Models\Pets\WxPetsAdoptionApply;
use App\Models\Pets\WxPetsAdoptionCollect;
use App\Models\Pets\WxPetsComment;
use App\Models\User\WxUser;
use App\Models\WxIcon;
use App\Models\WxSlideshow;
use App\Wen\Utils\BaiduUtils;
use App\Wen\Utils\GatewayUtils;
use App\Wen\Utils\ImageUtils;
use App\Wen\Utils\PetUtils;
use App\Wen\Utils\Settings;
use App\Wen\Utils\StrUtils;
use App\Wen\Utils\UserUtils;
use App\Wen\Utils\Utils;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PetsController extends BaseController{

    public function adoption_config(Request $request){
        $icon_id_arr = explode(',', Settings::get('pets_adoption_index_nav', ''));
        $config  = [
            'index' => [
                'banner' => WxSlideshow::wherein('id', explode(',', Settings::get('pets_adoption_index_banner', '', true)))->orderBy(DB::raw('FIND_IN_SET(id, "' . Settings::get('pets_adoption_index_banner', '', true) . '"' . ")"))->get(['id', 'poster', 'target_id', 'slideshow_type']),
                'notice' => Settings::get('pets_adoption_index_notice', [], true),
                'nav' => $icon_id_arr ? WxIcon::whereIn('id', $icon_id_arr)->orderBy(DB::raw('FIND_IN_SET(id, "' . implode(",", $icon_id_arr) . '"' . ")"))->get() : [],
                'count' => WxPetsAdoption::where('adopt_status', 1)->count()
            ]
        ];

        return $this->success($config);
    }

    public function adoption_list(Request $request){
        $uid = $request->uid;
        $limit = $request->input('limit', 10);
        $user_id = $request->user_id;
        $action = _empty_default_($request->action, 0);
        $keyword = _empty_default_($request->keyword, '');

        $filter_age_range = _empty_default_($request->filter_age_range, '');
        $filter_gender_range = _empty_default_($request->filter_gender_range, '');
        $filter_pet_status_range = _empty_default_($request->filter_pet_status_range, '');

        if(_empty_($user_id)){
            $user_id = null;
        }else{
            try {
                $user_id = _abs($user_id);
            }catch (\Exception $e){
                return $this->fail(200004, [], 'user_id参数错误');
            }
        }

        $species = $request->species;
        if(_empty_($species)){
            $species = 0;
        }

        $excludes = $request->excludes;
        if(_empty_($excludes)){
            $excludes = null;
        }else{
            if(is_array($excludes)){

            }else{
                $excludes = [$excludes];
            }
        }

        $city = $request->city;
        if(_empty_($city)){
            $city = null;
        }
        if($city == '全国' || $city == '重新定位' || $city == '定位中'){
            $city = null;
        }

        if(!in_array($species, [0, 1, 2])){
            return $this->fail(200004, [], '暂未开放其他物种');
        }
        $query = WxPetsAdoption::orderBy('adopt_status', 'asc')->orderBy('created_at', 'desc');
        if($species > 0){
            $query = $query->where('species', $species);
        }

        if($keyword){
            $query = $query->where(function ($query) use ($keyword) {
                if(is_numeric($keyword)){
                    $query->orWhere('id', $keyword)->orWhere('name', 'like', '%' . $keyword . '%')->orWhere('pet_breed', 'like', '%' . $keyword . '%');
                }else{
                    $query->orWhere('name', 'like', '%' . $keyword . '%')->orWhere('pet_breed', 'like', '%' . $keyword . '%');
                }
            });
        }

        if($city){
            if(!StrUtils::endsWith($city, '市')){
                $city .= '市';
            }
            if($keyword){

            }else{
                if($city == '北京市' || $city == '上海市' || $city == '重庆市' || $city == '天津市'){
                    $query = $query->where('province', 'like', $city.'%');
                }else{
                    $query = $query->where('city', 'like', $city.'%');
                }
            }
        }

        if($excludes){
            $query = $query->whereNotIn('id', $excludes);
        }

        if($user_id > 0){
            $query = $query->where('user_id', $user_id);
        }

        if($action > 0){
            if($action == 1){
                // 我的领养
                $adoption_arr = WxPetsAdoptionApply::where('user_id', $uid)->where('status', 1)->pluck('pet_adoption_id');
                $query = $query->whereIn('id', $adoption_arr);
            }else if($action == 2){
                // 我的送养
                $query = $query->where('user_id', $uid);
            }else if($action == 3){
                // 我的收藏
                $adoption_arr = WxPetsAdoptionCollect::where('user_id', $uid)->pluck('pet_adoption_id');
                $query = $query->whereIn('id', $adoption_arr);
            }else if($action == 4){
                // 已送养
                $query = $query->where('adopt_status', 1);
            }else if($action == 5){
                // 待送养
                $query = $query->where('adopt_status', 0);
            }
        }


        if($filter_age_range){
            // 1: 0-1岁  2:2-6岁 3:7-10岁
            if(StrUtils::startsWith($filter_age_range,'[')){
                $filter_age_range = ltrim($filter_age_range, '[');
                $filter_age_range = rtrim($filter_age_range, ']');
            }
            $filter_age_arr = explode(',', $filter_age_range);
            $arr_ = [];
            foreach ($filter_age_arr as $a){
                if($a == 1){
                    $arr_[] = ['pet_age', '>=', Carbon::now()->subYears(1)];
                }else if($a == 2){
                    $arr_[] = ['pet_age', '>=', Carbon::now()->subYears(6)];
                    $arr_[] = ['pet_age', '<=', Carbon::now()->subYears(2)];
                }else if($a == 3){
                    $arr_[] = ['pet_age', '<=', Carbon::now()->subYears(3)];
                }
            }
            $query = $query->Where($arr_);
        }

        if($filter_gender_range){
            if(StrUtils::startsWith($filter_gender_range,'[')){
                $filter_gender_range = ltrim($filter_gender_range, '[');
                $filter_gender_range = rtrim($filter_gender_range, ']');
            }
            // 1: 0-1岁  2:2-6岁 3:7-10岁
            $filter_gender_arr = explode(',', $filter_gender_range);
            $arr_ = [];
            if(count($filter_gender_arr) !== 2){
                foreach ($filter_gender_arr as $a){
                    if($a == 1){
                        $arr_[] = ['pet_gender', '=', 1];
                    }else if($a == 2){
                        $arr_[] = ['pet_gender', '=', 2];
                    }
                }
                $query = $query->Where($arr_);
            }

        }


        if($filter_pet_status_range){
            if(StrUtils::startsWith($filter_pet_status_range, '[')){
                $filter_pet_status_range = ltrim($filter_pet_status_range, '[');
                $filter_pet_status_range = rtrim($filter_pet_status_range, ']');
            }
            $filter_pet_status_arr = explode(',', $filter_pet_status_range);
            $arr_ = [];
            foreach ($filter_pet_status_arr as $a){
                if($a == 1){
                    $arr_[] = ['is_sterilization', '=', 1];
                }else if($a == 2){
                    $arr_[] = ['is_vaccine', '=', 1];
                }else if($a == 3){
                    $arr_[] = ['is_repellent', '=', 1];
                }
            }
            $query = $query->Where($arr_);

        }
        $data = $query->simplePaginate($limit);
        $data->map(function ($v, $k) use ($uid){
            return PetUtils::adoption_process($v, $uid);
        });
        return $this->success($data);
    }

    public function comment_process(Request $request){
        $action = _empty_default_($request->action, '');
        $uid = $request->uid;
        if(_empty_($action)){
            return $this->fail(200001);
        }
        if(!in_array($action, ['add', 'delete'])){
            return $this->fail(200004);
        }

        if(!UserUtils::is_user_can_speak($uid)){
            return $this->fail(200043, [
                'title' => '禁言中，无法言论',
                'content' => '是否前往解除限制',
                'confirmText' => '去解除',
                'target_type' => 6,
                'target_id' => '/pagesA/mine/unlock/unlock?user_id='.$uid
            ], '您当前处于禁言期间，无法言论');
        }

        if($action == 'add'){

            $pet_adoption_id = _empty_default_($request->pet_adoption_id, 0);
            if(_empty_($pet_adoption_id)){
                return $this->fail(200001);
            }

            if(!in_array(WxPetsAdoption::where('id', $pet_adoption_id)->value('adopt_status'), [0, 1])){
                return $this->fail(200000, [], '该领养不是正常状态');
            }

            if(mb_strlen( str_replace( [Settings::get('default_user_name', '微信用户'), '微信用户', '普通用户'], '', UserUtils::get_cached_user_name($uid) )) != mb_strlen(UserUtils::get_cached_user_name($uid))){
                return $this->fail(200041);
            }

            $comment_id = _empty_default_($request->comment_id, 0);
            if(_empty_($comment_id)){
                $comment_id = 0;
            }

            if($comment_id > 0){
                if(!WxPetsComment::where('id', $comment_id)->where('comment_state', 1)->exists()){
                    return $this->fail(200004, [], '该父级评论不存在');
                }
            }


            $comment_agent_id = _empty_default_($request->comment_agent_id, 0);
            if(_empty_($comment_agent_id)){
                $comment_agent_id = 0;
            }
            if($comment_agent_id > 0){
                $comment_agent_name = UserUtils::get_cached_user($comment_agent_id)['user_name'];
            }

            $comment_content = _empty_default_($request->comment_content, '');
            $comment_img_url = _empty_default_($request->comment_img_url, '');

            if(_empty_($comment_content)){
                return $this->fail(200001);
            }

            $comment_content = strip_tags($comment_content);
            if(mb_strlen($comment_content) <= 0 || mb_strlen($comment_content) > 240){
                return $this->fail(200004, [], '评论内容过长或过短');
            }

            global $__MINI_GLOBAL_IP__;

            // 百度审核
            if(UserUtils::user_permissions_check_by_config($uid, 'audit_pets_comment_white_list')){
                $need_manual_review = false;
            }else{
                $need_manual_review = true;
                $is_audit_pets_comment = Settings::get('is_audit_pets_comment', 0);
                if ($is_audit_pets_comment == 2) {
                    $filter_result = BaiduUtils::text_filter($comment_content);
                    if($filter_result){
                        if($filter_result['hit_level'] == 2){
                            // 不合规
                            return $this->fail(200016, ['tip'=>$filter_result['tip_list'], 'hit_word'=>$filter_result['hit_word']]);
                        }else if($filter_result['hit_level'] == 0){
                            // 审核通过
                            $need_manual_review = false;
                        }
                    }
                }else if($is_audit_pets_comment == 0){
                    $need_manual_review = true;
                }else{
                    $need_manual_review = false;
                }
            }

            // 0:审核中，1:审核通过，2:驳回
            $comment_state = 1;
            if($need_manual_review){
                $comment_state = 0;
            }


            $model = new WxPetsComment();
            $model->user_id = $uid;
            $model->pet_adoption_id = $pet_adoption_id;
            if($comment_id > 0){
                $model->comment_id = $comment_id;
            }else{
                $model->comment_id = 0;
            }
            if($comment_agent_id > 0 && $comment_agent_name){
                $model->comment_agent_id = $comment_agent_id;
                $model->comment_agent_name = $comment_agent_name;
            }else{
                $model->comment_agent_id = 0;
            }

            $model->comment_content = $comment_content;
            if(!_empty_($comment_img_url)){
                $model->comment_img_url = $comment_img_url;
            }

            if($__MINI_GLOBAL_IP__){
                $model->ip = $__MINI_GLOBAL_IP__;
            }
            $model->comment_state = $comment_state;
            $r = $model->save();
            if($r){
                return $this->success();
            }
            return $this->fail(200002);
        }else if($action == 'delete'){

        }
    }

    public function adoption_apply_action(Request $request){
        $apply_id = _empty_default_($request->apply_id, 0);
        $flag = _empty_default_($request->flag, 0);

        if(_empty_($apply_id)){
            return $this->fail(200004, [], 'apply_id参数错误');
        }

        $adopt_apply = WxPetsAdoptionApply::where('id', $apply_id)->first();
        if($adopt_apply->status == 1){
            return $this->fail(200010, [], '您已经处理过该申请');
        }
        if($adopt_apply->status == 2){
            return $this->fail(200010, [], '您已经拒绝了该申请');
        }

        DB::beginTransaction();
        try {
            WxPetsAdoptionApply::where('id',$apply_id )->update([
                'status' => $flag == 1 ? 1 : 2
            ]);
            if($flag == 1){
                // 自动拒绝其他的
                WxPetsAdoptionApply::where('pet_adoption_id',$adopt_apply->pet_adoption_id )->where('id', '<>', $apply_id)->where('status', 0)->update([
                    'status' => 2
                ]);
                WxPetsAdoption::where('id', $adopt_apply->pet_adoption_id)->update([
                    'adopt_status' => 1,
                    'success_user_id' => $adopt_apply->user_id
                ]);
            }
            DB::commit();
            return $this->success(['status'=>$flag ? 1 : 2]);
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return $this->fail(200002);
        }

    }

    public function adoption_collect(Request $request){
        $uid = $request->uid;
        $adoption_id = _empty_default_($request->id, 0);
        if(_empty_($adoption_id)){
            return $this->fail(200001);
        }
        if(WxPetsAdoptionCollect::where('user_id', $uid)->where('pet_adoption_id', $adoption_id)->exists()){
            WxPetsAdoptionCollect::where('user_id', $uid)->where('pet_adoption_id', $adoption_id)->delete();
        }else{
            $collect = new WxPetsAdoptionCollect();
            $collect->user_id = $uid;
            $collect->pet_adoption_id = $adoption_id;
            $collect->save();
        }
        return $this->success();
    }


    public function adoption_apply(Request $request){
        $uid = $request->uid;

        $pet_adoption_id = _empty_default_($request->pet_adoption_id);

        $the_adoption = WxPetsAdoption::where('id', $pet_adoption_id)->first();
        if(!$the_adoption){
            return $this->fail(200004, [], 'adoptionId参数错误');
        }
        if($the_adoption->adopt_status == 1){
            return $this->fail(200004, [], '该宠物已被领养');
        }
        if($the_adoption->adopt_status == 2){
            return $this->fail(200004, [], '该领养信息已废弃');
        }

        $the_apply = WxPetsAdoptionApply::where('pet_adoption_id', $the_adoption->id)->where('user_id', $uid)->first();
        if($the_apply && $the_apply->status == 1){
            _logger_(__file__, __line__, '出现逻辑错误');
            return $this->fail(200004, [], '您的申请已经通过了');
        }

        $gender = _empty_default_($request->gender, 0);
        if(!in_array($gender, [0, 1, 2])){
            return $this->fail(200004, [], '性别参数错误');
        }
        $is_experience = _empty_default_($request->is_experience, 0);
        if(!in_array($is_experience, [0, 1])){
            return $this->fail(200004, [], '养宠经验参数错误');
        }
        // 0：单身 1：恋爱中 2：已婚
        $marital_status = _empty_default_($request->marital_status, 0);
        if(!in_array($marital_status, array_keys(PetUtils::marital_status()))){
            return $this->fail(200004, [], '婚姻状况参数错误');
        }
        // 0: 自住房 1：整租房 2：合租
        $housing_status = _empty_default_($request->housing_status, 0);
        if(!in_array($housing_status, array_keys(PetUtils::housing_status()))){
            return $this->fail(200004, [], '房屋情况参数错误');
        }
        // 0: 无业 1: 学生 2:工作 3: 退休
        $working_status = _empty_default_($request->working_status, 0);
        if(!in_array($working_status, array_keys(PetUtils::working_status()))){
            return $this->fail(200004, [], '工作状态参数错误');
        }

        $job = _empty_default_($request->job);
        $birthday = _empty_default_($request->birthday);
        try {
            $age_timestamp = strtotime($birthday);
        }catch (\Exception $e){
            return $this->fail(200004, [], '生日不合法');
        }

        if((time() - $age_timestamp) < (31536000 * 18)){
            return $this->fail(200004, [], '未成年不能申请');
        }

        // 0:小于3千 1:3千～6千 2:6千～1万 3:1万以上
        $income = _empty_default_($request->income, 0);
        if(!in_array($income, array_keys(PetUtils::income_types()))){
            return $this->fail(200004, [], '收入参数错误');
        }
        $wechatId = _empty_default_($request->wechatId);

        $mobile = _empty_default_($request->mobile);
        $remark = _empty_default_($request->remark);
        $region = _empty_default_($request->region, []);
        if(count($region) !== 3){
            return $this->fail(200004, [], '请选择完整的地址');
        }

        if(_empty_($pet_adoption_id) || _empty_($job) || _empty_($age_timestamp) || _empty_($wechatId) || _empty_($mobile) || _empty_($remark)){
            return $this->fail(200001);
        }
        DB::beginTransaction();
        try {
            // todo:
            if($the_apply && $the_apply->status == 0){
                $apply = $the_apply;
            }else{
                $apply = new WxPetsAdoptionApply();
            }

            $apply->user_id = $uid;
            $apply->pet_adoption_id = $pet_adoption_id;
            $apply->gender = $gender;
            $apply->is_experience = $is_experience;
            $apply->marital_status = $marital_status;
            $apply->housing_status = $housing_status;
            $apply->working_status = $working_status;
            $apply->job = $job;
            $apply->birthday = timetostr($age_timestamp);
            $apply->income = $income;

            $apply->province = $region[0];
            $apply->city = $region[1] == '市辖区' ? $region[0] : $region[1];;
            $apply->district = $region[2];


            $apply->mobile = $mobile;
            $apply->wechatId = $wechatId;
            $apply->remark = $remark;
            $r = $apply->save();
            if($r){
                $model = WxContRepositories::add($uid, $the_adoption->user_id, null, null, null, 0, null, $apply->id);
                DB::commit();
                return $this->success(['id'=>$apply->id, 'object_id'=>$the_adoption->user_id], 200, '发送成功');
            }else{
                DB::rollBack();
                return $this->fail(200006);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return false;
        }
    }

    public function comment_list(Request $request){
        $limit = _between_(_empty_default_($request->limit, 10), 1, 100);
        $pet_adoption_id = _empty_default_($request->pet_adoption_id, 0);
        if(_empty_($pet_adoption_id)){
            $this->fail(200001);
        }
        $data = WxPetsComment::where('pet_adoption_id', $pet_adoption_id)->where('comment_id', 0)->where('comment_state', 1)->orderBy('id', 'desc')->simplePaginate($limit);
        if($data){
            $data->map(function ($v, $k){
                $v->user = UserUtils::get_cached_user($v->user_id);
                if(_empty_($v->comment_id)){
                    $childData = WxPetsComment::where('comment_id', $v->id)->limit(100)->get();
                    if($childData){
                        $childData->map(function ($v2, $k2){
                            $v2->user = UserUtils::get_cached_user($v2->user_id);
                            $v2->format_time = format_datetime($v2->created_at);
                            return $v2;
                        });
                    }
                    $v->child = $childData;
                }else{
                    $v->child = [];
                }
                $v->format_time = format_datetime($v->created_at);
                return $v;
            });
            return $this->success($data);
        }else{
            return $this->fail(200003);
        }
    }

    public function adoption_detail(Request $request){
        $id = _empty_default_($request->id, 0);
        $uid = $request->uid;
        if(_empty_($id)){
            return $this->fail(200001);
        }
        $adoption = WxPetsAdoption::where('id', $id)->first();
        $user_info_img = Settings::get('pets_adoption_detail_user_info_img', 0);
        if($user_info_img > 0){
            $adoption->user_info_img = WxIcon::find($user_info_img);
        }else{
            $adoption->user_info_img = null;
        }
        $adoption->comment_count = WxPetsComment::where('pet_adoption_id', $adoption->id)->count();
        if($adoption){
            return $this->success(PetUtils::adoption_process($adoption, $uid));
        }else{
            return $this->fail(200003);
        }
    }

    public function adoption_add(Request $request){
        global $__MINI_GLOBAL_CURRENT_PLAYER_ID__;
        $id = _empty_default_($request->id, 0);
        $name = _empty_default_($request->name, '');
        $pictures = _empty_default_($request->pictures, []);
        $pet_gender = _empty_default_($request->pet_gender, 0);
        $species = _empty_default_($request->species, 0);
        $pet_breed = _empty_default_($request->pet_breed);
        $is_vaccine = _empty_default_($request->is_vaccine, 0);
        $is_sterilization = _empty_default_($request->is_sterilization, 0);
        $is_repellent = _empty_default_($request->is_repellent, 0);
        $is_free = _empty_default_($request->is_free, 0);
        $cost = _empty_default_($request->cost, 0);
        $pet_introduce = _empty_default_($request->pet_introduce);
        $condition = _empty_default_($request->condition, []);
        $region = _empty_default_($request->region, []);
        $address = _empty_default_($request->address);
        $adopter_name = _empty_default_($request->adopter_name);
        $adopter_mobile = _empty_default_($request->adopter_mobile, '');
        $adopter_wechatId = _empty_default_($request->adopter_wechatId);
        $adopt_status = _empty_default_($request->adopt_status, 0);

        $video_url = _empty_default_($request->video_url, null);
        $video_cover = _empty_default_($request->video_cover, null);

        $age_range = _empty_default_($request->age_range, 0);

        $image_state_change_list = [];

        $uid = $request->uid;

        $user = WxUser::find($uid);
        // 验证资料
        if(Settings::get('pets_adoption_add_force_bind_phone', 0, true) == 1){
            if(_empty_($user->phone) && _empty_($__MINI_GLOBAL_CURRENT_PLAYER_ID__)){
                return $this->fail(200043, [
                    'title' => '未绑定手机号',
                    'content' => '前往绑定',
                    'confirmText' => '去绑定',
                    'target_type' => 6,
                    'target_id' => '/pagesA/mine/editmine/editmine?phone=1'
                ], '未绑定手机号');
            }
        }

        if(Settings::get('pets_adoption_add_force_real_name', 0, true) == 1){
            if(_empty_($user->real_name) && _empty_($__MINI_GLOBAL_CURRENT_PLAYER_ID__)){
                return $this->fail(200043, [
                    'title' => '未实名认证',
                    'content' => '您还没有实名认证，是否前往认证',
                    'confirmText' => '去认证',
                    'target_type' => 6,
                    'target_id' => '/pagesA/mine/realname/realname'
                ], '未实名认证');
            }
        }

        try {
            $cost = round($cost, 2);
        }catch (\Exception $e){
            return $this->fail(200004, [], '金额不合法');
        }

        $the_adoption = null;
        if($id > 0){
            $the_adoption = WxPetsAdoption::find($id);
            if($the_adoption->adopt_status == 1){
                return $this->fail(200004, [], '领养已经完成，无法再更改');
            }
        }

        global $__MINI_GLOBAL_IP__;

        // 1、必选信息做检查
        if(_empty_($name) || _empty_($pictures) || _empty_($pet_introduce) || _empty_($region) || _empty_($address) || _empty_($adopter_name) || _empty_($adopter_wechatId)){
            return $this->fail(200001);
        }

        if(count($region) !== 3){
            return $this->fail(200004, [], '请选择完整的地址');
        }

        try {
            $age_timestamp = PetUtils::age_range_transfer($age_range, null);
        }catch (\Exception $e){
            return $this->fail(200004, [], '宠物生日不合法');
        }

        if((time() - $age_timestamp) < (20 * 24 * 3600)){
            return $this->fail(200004, [], '小于20天的不方便进行发布领养');
        }

        if(!in_array($species, [1, 2])){
            return $this->fail(200004, [], '暂时只开放猫咪和狗狗的领养');
        }

        if(!in_array($is_free, [0, 1, 2])){
            return $this->fail(200004, [], '暂时只开放猫咪和狗狗的领养');
        }else{
            if($is_free == 1){
                // 有偿
                if($cost < 1){
                    return $this->fail(200004, [], '请设置有偿领养的价格');
                }
            }else if($is_free == 2){
                if($cost < 1){
                    return $this->fail(200004, [], '请设置押金具体金额');
                }
            }else{
                $isFree = 0;
                $cost = 0;
            }
        }

        if(!in_array($pet_gender, [0, 1, 2])){
            return $this->fail(200004, [], '宠物性别不合法');
        }

        if(!in_array($is_vaccine, [0, 1]) || !in_array($is_sterilization, [0, 1]) || !in_array($is_repellent, [0, 1])){
            return $this->fail(200004, [], '参数错误');
        }

        $condition_ = [];
        if($condition){
            $condition = array_unique($condition);
            foreach ($condition as $c){
                if(in_array($c, array_keys(PetUtils::adoption_condition()))){
                    $condition_[] = $c;
                }
            }
        }


        $pictures_ = [];
        if($pictures){
            foreach ($pictures as $pic){
                $pictures_[] = [
                    'type' => 'img',
                    'url' => $pic['url']
                ];
                $image_state_change_list[] = $pic['url'];
            }
        }else{
            return $this->fail(200004, [], '图片参数错误');
        }

        if(_empty_($video_url)){
            $video_cover = null;
        }


        if(!_empty_($video_url)){
            if(_empty_($video_cover)){
                $res = ImageUtils::upload_video_screenshot($video_url);
                if($res && $res['url']){
                    $video_cover = $res['url'];
                }
            }
        }

        if($video_url){
            $image_state_change_list[] = $video_url;
            if($video_cover){
                $image_state_change_list[] = $video_cover;
            }
        }


        // 百度审核
        if(UserUtils::user_permissions_check_by_config($uid, 'audit_pets_adoption_white_list')){
            $need_manual_review = false;
        }else{
            $need_manual_review = true;
            $is_audit_pets_adoption = Settings::get('is_audit_pets_adoption', 0);
            if ($is_audit_pets_adoption == 2) {
                $filter_result = BaiduUtils::text_filter($name);
                if($filter_result){
                    if($filter_result['hit_level'] == 2){
                        // 不合规
                        return $this->fail(200016, ['tip'=>$filter_result['tip_list'], 'hit_word'=>$filter_result['hit_word']]);
                    }else if($filter_result['hit_level'] == 0){
                        // 审核通过
                        $need_manual_review = false;
                    }
                }
            }else if($is_audit_pets_adoption == 0){
                $need_manual_review = true;
            }else{
                $need_manual_review = false;
            }
        }

        // 0:审核中，1:审核通过，2:驳回
        if($need_manual_review){
            $adopt_status = 3;
        }

        if($the_adoption){
            $adoption = $the_adoption;
        }else{
            $adoption = new WxPetsAdoption();
            $adoption->user_id = $uid;
        }

        $adoption->name = $name;
        $adoption->pictures = json_encode($pictures_);
        if($video_url){
            $adoption->video_url = $video_url;
            $adoption->video_cover = $video_cover;
        }

        $adoption->species = $species;
        $adoption->pet_breed = $pet_breed;
        $adoption->is_free = $is_free;
        $adoption->cost = $cost;
        $adoption->pet_gender = $pet_gender;
        $adoption->pet_age = timetostr($age_timestamp);
        $adoption->is_vaccine = $is_vaccine;
        $adoption->is_sterilization = $is_sterilization;
        $adoption->is_repellent = $is_repellent;
        $adoption->pet_introduce = $pet_introduce;
        $adoption->condition = implode(',', $condition_);

        $adoption->province = $region[0];
        $adoption->city = $region[1] == '市辖区' ? $region[0] : $region[1];
        $adoption->district = $region[2];
        $adoption->address = $address;

        $adoption->adopter_name = $adopter_name;
        if($adopter_mobile){
            $adoption->adopter_mobile = $adopter_mobile;
        }
        $adoption->adopter_wechatId = $adopter_wechatId;

        $adoption->adopter_ip = $__MINI_GLOBAL_IP__;
        if($the_adoption){
            $adoption->adopt_status = $adopt_status;
        }else{
            $adoption->adopt_status = 0;
        }

        $r = $adoption->save();
        if($r){
            Utils::image_state_change($image_state_change_list, 1);
            return $this->success(['id'=>$adoption->id]);
        }else{
            return $this->fail(200006);
        }
    }
}
